﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WeiTalk.SinaEntities.Status;
using System.Windows.Media.Imaging;
using ImageTools.IO.Gif;
using System.IO;
using System.Text.RegularExpressions;
using ImageTools.IO.Bmp;
using ImageTools.Controls;

namespace WeiTalk.Controls
{
    public class ImageEventArgs
    {
        public string ImageUrl { get; set; }
    }
    public delegate void ClickEventHandler(object sender, EventArgs e);
    public delegate void ImageClickEventHandler(object sender, ImageEventArgs e);
    public partial class WeiBoControl : UserControl
    {
        #region properties
        public static readonly DependencyProperty UserNameProperty =
       DependencyProperty.Register(
       "UserName", typeof(string),
       typeof(WeiBoControl), null
       );
        public string UserName
        {
            get
            {
                return (string)GetValue(UserNameProperty);
            }
            set
            {
                SetValue(UserNameProperty, value);
            }
        }

        public static readonly DependencyProperty CreatedAtProperty =
        DependencyProperty.Register(
        "CreatedAt", typeof(string),
        typeof(WeiBoControl), null
        );
        public string CreatedAt
        {
            get
            {
                return (string)GetValue(CreatedAtProperty);
            }
            set
            {
                SetValue(CreatedAtProperty, value);
            }
        }

        public static readonly DependencyProperty ProfileImageUrlProperty =
        DependencyProperty.Register(
        "ProfileImageUrl", typeof(ImageSource),
        typeof(WeiBoControl), null
        );
        public ImageSource ProfileImageUrl
        {
            get
            {
                return (ImageSource)GetValue(ProfileImageUrlProperty);
            }
            set
            {
                if (value != null)
                {
                    SetValue(ProfileImageUrlProperty, value);
                    headImg.Source = value;
                }
            }
        }

        public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(
        "Text", typeof(string),
        typeof(WeiBoControl), null
        );
        public string Text
        {
            get
            {
                return (string)GetValue(TextProperty);
            }
            set
            {
                SetValue(TextProperty, value);
            }
        }

        public static readonly DependencyProperty RetweetedContentProperty =
            DependencyProperty.Register("RetweetedContent", typeof(string), typeof(WeiBoControl), null);
        public string RetweetedContent
        {
            get { return (string)GetValue(RetweetedContentProperty); }
            set { SetValue(RetweetedContentProperty, value); }
        }

        public static readonly DependencyProperty RetweetedUserNameProperty =
            DependencyProperty.Register("RetweetedUserName", typeof(string), typeof(WeiBoControl), null);
        public string RetweetedUserName
        {
            get { return (string)GetValue(RetweetedUserNameProperty); }
            set { SetValue(RetweetedUserNameProperty, value); }
        }

        public static readonly DependencyProperty RetweetedCreateAtProperty =
           DependencyProperty.Register("RetweetedCreateAt", typeof(string), typeof(WeiBoControl), null);
        public string RetweetedCreateAt
        {
            get { return (string)GetValue(RetweetedCreateAtProperty); }
            set { SetValue(RetweetedCreateAtProperty, value); }
        }

        public static readonly DependencyProperty ThumbnailPicProperty =
          DependencyProperty.Register("ThumbnailPic", typeof(string), typeof(WeiBoControl), null);
        public string ThumbnailPic
        {
            get { return (string)GetValue(ThumbnailPicProperty); }
            set
            {
                SetValue(ThumbnailPicProperty, value);
                try
                {
                    WeiBoUtility.RetrieveImage(ThumbnailPic, s =>
                    {
                        CreateWeiBoImageControl("imgWeiBo", s, spImageWeiBo, Regex.IsMatch(value, ".gif$", RegexOptions.IgnoreCase), imgWeiBo_MouseLeftButtonUp, imgWeiBo_MouseLeftButtonDown);
                    }, Dispatcher.BeginInvoke);
                }
                catch
                {
                    spImageWeiBo.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        public string OriginalPic
        {
            get;
            set;
        }

        public string RetweetedOriginalPic
        { get; set; }

        public static readonly DependencyProperty RetweetedThumbnailPicProperty =
          DependencyProperty.Register("RetweetedThumbnailPic", typeof(string), typeof(WeiBoControl), null);
        public string RetweetedThumbnailPic
        {
            get { return (string)GetValue(RetweetedThumbnailPicProperty); }
            set
            {
                SetValue(RetweetedThumbnailPicProperty, value);
                try
                {
                    WeiBoUtility.RetrieveImage(value, s =>
                    {
                        CreateWeiBoImageControl("imgRetweetedWeiBo", s, spImgRetweetedWeiBo, Regex.IsMatch(value, ".gif$", RegexOptions.IgnoreCase), imgRetweetedWeiBo_MouseLeftButtonUp, imgRetweetedWeiBo_MouseLeftButtonDown);
                    }, Dispatcher.BeginInvoke);

                    spImgRetweetedWeiBo.Visibility = System.Windows.Visibility.Visible;
                }
                catch
                {
                    spImgRetweetedWeiBo.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        public static readonly DependencyProperty SourceProperty =
          DependencyProperty.Register("Source", typeof(string), typeof(WeiBoControl), null);
        public string Source
        {
            get { return (string)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty RetweetedSourceProperty =
          DependencyProperty.Register("RetweetedSource", typeof(string), typeof(WeiBoControl), null);
        public string RetweetedSource
        {
            get { return (string)GetValue(RetweetedSourceProperty); }
            set { SetValue(RetweetedSourceProperty, value); }
        }

        public string RetweetedCommentCount
        { get; set; }

        public string RetweetedRepostsCount
        { get; set; }

        public string CommentCount
        { get; set; }

        public string RepostsCount
        {
            get;
            set;
        }

        public string Id
        { get; set; }

        public string UserId
        { get; set; }

        public string RetweetedId
        {
            get;
            set;
        }

        public string RetweetedUserId
        {
            get;
            set;
        }

        public Storyboard ClickStoryboard
        {
            get { return sbSelected; }
        } 
        #endregion

        public event ClickEventHandler Click;
        public event ImageClickEventHandler ThumbnailPicClick;
        public event ImageClickEventHandler RetweetedThumbnailPicClick;

        const int clickYDistance = 50;
        const int clickXDistance = 5;
        double perThumbnailMouseY = 0d;
        double perThumbnailMouseX = 0d;
        double perRetweetedThumbnailMouseY = 0d;
        double perRetweetedThumbnailMouseX = 0d;
        double perMouseY = 0d;
        double perMouseX = 0d;

        public WeiBoControl()
        {
            InitializeComponent();
            this.Visibility = System.Windows.Visibility.Collapsed;
        }

        private UIElement CreateWeiBoImageControl(string name, Stream s, StackPanel parentControl, bool isGif, MouseButtonEventHandler upEvent,MouseButtonEventHandler downEvent)
        {
            UIElement imageControl = null;
            if (isGif)
            {
                imageControl = new AnimatedImage
                {
                    Name = name,
                    Width = 150,
                    Height = 150,
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    Margin = new Thickness { Left = 5 },
                    Stretch = Stretch.Uniform
                };
                imageControl.MouseLeftButtonUp += new MouseButtonEventHandler(upEvent);
                imageControl.MouseLeftButtonDown += new MouseButtonEventHandler(downEvent);
                parentControl.Children.Add(imageControl);
                ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
                ImageTools.ExtendedImage image = new ImageTools.ExtendedImage();
                GifDecoder decoder = new GifDecoder();
                decoder.Decode(image, s);
                ((AnimatedImage)imageControl).Source = image;
            }
            else
            {
                imageControl = new Image
                {
                    Name = name,
                    Width = 150,
                    Height = 150,
                    HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                    Margin = new Thickness { Left = 5 },
                    Stretch = Stretch.Uniform
                };
                imageControl.MouseLeftButtonUp += new MouseButtonEventHandler(upEvent);
                imageControl.MouseLeftButtonDown += new MouseButtonEventHandler(downEvent);
                parentControl.Children.Add(imageControl);

                BitmapImage bi = new BitmapImage();
                bi.SetSource(s);
                bi.CreateOptions = BitmapCreateOptions.BackgroundCreation;
                ((Image)imageControl).Source = bi;
            }
            return imageControl;
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            spRetweeted.Visibility = System.Windows.Visibility.Collapsed;
            tbUserName.Text = UserName;
            tbCreateAt.Text = CreatedAt;

            tbSource.Text = Source;
            tbRetweetedSource.Text = RetweetedSource;
            tbRepostsCount.Text = "转发: " + RepostsCount;
            tbCommentsCount.Text = "评论: " + CommentCount;

            //微博图片
            if (ThumbnailPic == null)
            {
                spImageWeiBo.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                spImageWeiBo.Visibility = System.Windows.Visibility.Visible;
            }
            //转发内容
            if (!String.IsNullOrEmpty(RetweetedContent))
            {
                spRetweeted.Visibility = System.Windows.Visibility.Visible;
                tbRetweetedContent.Text = RetweetedContent;

                if (!String.IsNullOrEmpty(RetweetedUserName))
                {
                    tbRetweetedUserName.Text = "@" + RetweetedUserName;
                    tbRetweetedCreateAt.Text = RetweetedCreateAt;
                }
                //转发微博的图片
                if (RetweetedThumbnailPic != null)
                {
                    spImgRetweetedWeiBo.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    spImgRetweetedWeiBo.Visibility = System.Windows.Visibility.Collapsed;
                }
                if (!String.IsNullOrEmpty(RetweetedCommentCount))
                {
                    tbRetweetedCommentsCount.Text = "评论: " + RetweetedCommentCount;
                }
                else
                {
                    tbRetweetedCommentsCount.Text = "";
                }
                if (!String.IsNullOrEmpty(RetweetedRepostsCount))
                {
                    tbRetweetedRepostsCount.Text = "转发: " + RetweetedRepostsCount;
                }
                else
                {
                    tbRetweetedRepostsCount.Text = "";
                }
            }
            else
            {
                spRetweeted.Visibility = System.Windows.Visibility.Collapsed;
            }
            tbContent.Text = Text;
            this.Visibility = System.Windows.Visibility.Visible;
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Click != null)
            {
                perMouseY = e.GetPosition(null).Y;
                perMouseX = e.GetPosition(null).X;
                e.Handled = true;
            }
        }

        private void Border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (Click != null)
            {
                if (Math.Abs(perMouseY - e.GetPosition(null).Y) < clickXDistance &&
                    Math.Abs(perMouseX - e.GetPosition(null).X) < clickYDistance)
                {
                    OnClick(e);
                    e.Handled = true;
                }
            }
        }

        private void OnClick(EventArgs e)
        {
            if (Click != null)
            {
                Click(this, e);
            }
        }

        private void imgWeiBo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (ThumbnailPicClick != null)
            {
                if (Math.Abs(perThumbnailMouseY - e.GetPosition(null).Y) < clickYDistance &&
                   Math.Abs(perThumbnailMouseX - e.GetPosition(null).X) < clickXDistance)
                {
                    ImageEventArgs ie = new ImageEventArgs { ImageUrl = OriginalPic };
                    ThumbnailPicClick(this, ie);
                    e.Handled = true;
                }
            }
        }

        private void imgWeiBo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ThumbnailPicClick != null)
            {
                perThumbnailMouseX = e.GetPosition(null).X;
                perThumbnailMouseY = e.GetPosition(null).Y;
                e.Handled = true;
            }
        }

        private void imgRetweetedWeiBo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (RetweetedThumbnailPicClick != null)
            {
                if (Math.Abs(perRetweetedThumbnailMouseY - e.GetPosition(null).Y) < clickYDistance &&
                   Math.Abs(perRetweetedThumbnailMouseX - e.GetPosition(null).X) < clickXDistance)
                {
                    ImageEventArgs ie = new ImageEventArgs { ImageUrl = RetweetedOriginalPic };
                    RetweetedThumbnailPicClick(this, ie);
                    e.Handled = true;
                }
            }
        }

        private void imgRetweetedWeiBo_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (RetweetedThumbnailPicClick != null)
            {
                perRetweetedThumbnailMouseX = e.GetPosition(null).X;
                perRetweetedThumbnailMouseY = e.GetPosition(null).Y;
                e.Handled = true;
            }
        }
    }
}
